<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<script type="text/javascript">
    require([ "dojo/_base/array", "dojo/_base/xhr", "dojo/request", "dojo/topic", "dojo/json", "dijit/Dialog" ], function(array, xhr,
            request, topic, JSON, Dialog) {
        var deletItemsCount = 0;
        var refreshTree = "sysmenu/refreshZtree";
        var nodeObj = null;
        topic.subscribe("refreshAttachGrid", function() {
            var currentPage = jQuery('#attachmentGird').jqGrid('getGridParam', 'page');
            var pageSize = jQuery('#attachmentGird').jqGrid('getGridParam', 'rowNum');
            var totalCount = jQuery('#attachmentGird').jqGrid('getGridParam', 'records') - deletItemsCount;
            var totalPages = Math.ceil(totalCount / pageSize);
            jQuery("#attachmentGird").jqGrid('setGridParam', {
                page : currentPage > totalPages ? totalPages : currentPage
            }).trigger("reloadGrid");
        });
        attachcatalogRestForm = function(type) {
            var form = attachcatalogIFD;
            if (type == 'u') {
                form = attachcatalogUFD;
                form.reset();
                nodeObj = nodeObj || {};
                form.setValues(nodeObj);
            }else{
                form.reset();
            }
        };
        topic.subscribe("attachcatalog/insertOrUpdate", attachcatalogRestForm);
        var syncDB = function(url, jsonData) {
            request.post(url, {
                data : jsonData,
                headers : {
                    'Content-Type' : "application/json; charset=utf-8"
                },
                timeout : 30000
            }).then(function(response) {
                topic.publish("notifyMsgTopic", {
                    message : response,
                    type : "message",
                    duration : 1000
                });
                topic.publish(refreshTree);
                topic.publish("refreshAttachGrid");
            }, function(error) {
                alert(error);
            });
        };
        attachcatalogSubmitForm = function(formId, type) {
            var url = "attachcatalog/insert";
            var form = attachcatalogIFD;
            if (type == 'u') {
                form = attachcatalogUFD;
                url = "attachcatalog/update";
            }
            if (form.isValid()) {
                var json = JSON.stringify(form.getValues());
                syncDB(url, json);
                form.hide();
                topic.publish("attachcatalog/insertOrUpdate", formId);
            } else {
                form.validate();
            }
        };
        attachmentDelete = function() {
            var ids = jQuery("#attachmentGird").jqGrid('getGridParam', 'selarrrow') || [];
            deletItemsCount = ids.length;
            if (ids.length > 0) {
                if (confirm('确认删除所选定的项？')) {
                    var attachment = {};
                    attachment.id = '';
                    array.forEach(ids, function(entry, i) {
                        attachment.id += entry + ",";
                    });
                    syncDB("attachment/delete", JSON.stringify(attachment));
                }
            } else {
                alert('请选择至少一条数据!');
            }
        };
        attachUploadDialog = new Dialog({
            title: "附件上传",
            style: "width: 800px",
            onHide: function() {
                topic.publish("refreshAttachGrid");
            }
        });
        // zTree
        var addHoverDom = function(treeId, treeNode) {
            var sObj = jQuery("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || jQuery("#addBtn_" + treeNode.id).length > 0)
                return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.id
                    + "' title='新增节点' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = jQuery("#addBtn_" + treeNode.id);
            if (btn) {
                btn.bind("click", function() {
                    var zTree = jQuery.fn.zTree.getZTreeObj(treeId);
                    if (!treeNode.open) {
                        zTree.expandNode(treeNode);
                    }
                    attachcatalogIFD.setValues({
                        pid : treeNode.catalogId,
                        creatorId : username
                    });
                    attachcatalogIFD.show();
                    var handle = topic.subscribe(refreshTree, function() {
                        if (treeNode.isParent) {
                            zTree.reAsyncChildNodes(treeNode, "refresh");
                        } else {
                            zTree.reAsyncChildNodes(treeNode.getParentNode(), "refresh");
                        }
                        handle.remove();
                    });
                    return false;
                });
            }
        };
        var removeHoverDom = function(treeId, treeNode) {
            jQuery("#addBtn_" + treeNode.id).unbind().remove();
        };
        var setRemoveBtn = function(treeId, treeNode) {
            return treeNode.level;
        };
        var setRenameBtn = function(treeId, treeNode) {
            return treeNode.level;
        };
        var onClick = function(event, treeId, treeNode, clickFlag) {
            jQuery("#attachmentGird").jqGrid('setGridParam', {
                postData: {catalogid : treeNode.catalogId},
                mtype : 'post'
            }).trigger("reloadGrid");
        };
        var setting = {
            async : {
                enable : true,
                url : "attachcatalog/zTree",
                autoParam : [ "catalogId" ]
            },
            view : {
                addHoverDom : addHoverDom,
                removeHoverDom : removeHoverDom,
                selectedMulti : false
            },
            edit : {
                enable : true,
                editNameSelectAll : true,
                showRenameBtn : setRenameBtn,
                showRemoveBtn : setRemoveBtn
            },
            data : {
                key : {
                    name : 'catalogName'
                },
                simpleData : {
                    enable : true,
                    idKey : 'catalogId',
                    pIdKey : 'pid'
                }
            },
            callback : {
                onClick : onClick,
                beforeEditName : function(treeId, treeNode) {
                    nodeObj = treeNode;
                    attachcatalogUFD.setValues(treeNode);
                    attachcatalogUFD.show();
                    var zTree = jQuery.fn.zTree.getZTreeObj(treeId);
                    var handle = topic.subscribe(refreshTree, function() {
                        zTree.reAsyncChildNodes(treeNode.getParentNode() || treeNode, "refresh");
                        handle.remove();
                    });
                    return false;
                },
                beforeRemove : function(treeId, treeNode) {
                    return confirm("确认删除?");
                },
                onRemove : function(event, treeId, treeNode) {
                    var attachcatalog = {};
                    attachcatalog.id = treeNode.catalogId;
                    syncDB("attachcatalog/delete", JSON.stringify(attachcatalog));
                }
            }
        };
        jQuery.fn.zTree.init(jQuery("#attachCatalogTree"), setting);
    });
</script>
<div data-dojo-type="dijit/Dialog" data-dojo-id="attachcatalogIFD" title="新增">
  <div class="dijitDialogPaneContentArea">
    <input data-dojo-type="dijit/form/ValidationTextBox" type="text" name="pid" style="display: none;">
    <input data-dojo-type="dijit/form/ValidationTextBox" type="text" name="creatorId" style="display: none;">
    <table>
      <tr>
        <td><label for="catalogname">分类名称: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true"
          type="text" name="catalogName"></td>
      </tr>
      <tr>
        <td><label for="catalogpath">分类路径: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true"
          type="text" name="catalogPath"></td>
      </tr>
      <tr>
        <td><label for="isshare">是否共享: </label></td>
        <td>
          <select data-dojo-type="dijit/form/Select" name="isShare" data-dojo-props="required: true, trim:true" style="width: 182px;">
            <option value="1">共享</option>
            <option value="0">不共享</option>
          </select>
        </td>
      </tr>
    </table>
  </div>
  <div class="dijitDialogPaneActionBar">
    <button data-dojo-type="dijit/form/Button" type="button" onclick="attachcatalogSubmitForm('','i')">保存</button>
    <button data-dojo-type="dijit/form/Button" type="button" onclick="attachcatalogRestForm('IFD');">重置</button>
  </div>
</div>
<div data-dojo-type="dijit/Dialog" data-dojo-id="attachcatalogUFD" title="更新">
  <div class="dijitDialogPaneContentArea">
    <input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, readOnly: true" type="text"
      name="catalogId" style="display: none;"> <input data-dojo-type="dijit/form/ValidationTextBox"
      data-dojo-props="required: true, readOnly: true" type="text" name="pid" style="display: none;"> <input
      data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, readOnly: true" type="text"
      name="creatorId" style="display: none;"> <input data-dojo-type="dijit/form/ValidationTextBox"
      data-dojo-props="required: true, readOnly: true" type="text" name="createTime" style="display: none;">
    <table>
      <tr>
        <td><label for="catalogname">分类名称: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text"
          name="catalogName"></td>
      </tr>
      <tr>
        <td><label for="catalogpath">分类路径: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text"
          name="catalogPath"></td>
      </tr>
      <tr>
        <td><label for="isshare">是否共享: </label></td>
        <td>
          <select data-dojo-type="dijit/form/Select" name="isShare" data-dojo-props="required: true, trim:true" style="width: 182px;">
            <option value="1">共享</option>
            <option value="0">不共享</option>
          </select>
        </td>
      </tr>
    </table>
  </div>
  <div class="dijitDialogPaneActionBar">
    <button data-dojo-type="dijit/form/Button" type="button" onclick="attachcatalogSubmitForm('','u')">保存</button>
    <button data-dojo-type="dijit/form/Button" type="button" onclick="attachcatalogRestForm('UFD');">重置</button>
  </div>
</div>
<div style="height: 100%; width: 100%; margin: 0; padding: 0;" data-dojo-type="dijit/layout/BorderContainer"
  data-dojo-props="design: 'headline'">
  <div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'center'">
    <div style="width: 690px;">
      <table id="attachmentGird"></table>
      <div id="attachmentToolbar"></div>
    </div>
  </div>
  <div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="splitter: true, region: 'left'" style="width: 150px;">
    <div>
      <ul id="attachCatalogTree" class="ztree"
        style="margin: 0px; padding: 0; border: 0 solid white; background: white; overflow-y: hidden;"></ul>
    </div>
  </div>
</div>
<script type="text/javascript">
    var iconFmt = function(fileName, fileType) {
        var imgHtml = "";
        if (fileType.indexOf("zip") != -1) {
            imgHtml = "<img src='resources/MEDIA/images/file/zip.gif' width=50 height=50/>";
        } else if (fileType.indexOf("rar") != -1) {
            imgHtml = "<img src='resources/MEDIA/images/file/rar.gif' width=50 height=50/>";
        } else if (fileType.indexOf("pdf") != -1) {
            imgHtml = "<img src='resources/MEDIA/images/file/pdf.gif' width=50 height=50/>";
        } else if (fileType.indexOf("msword") != -1) {
            var ext = "doc";
            if(fileName.indexOf("ppt") != -1){
                ext = "ppt";
            }else if(fileName.indexOf("xls") != -1){
                ext = "xls";
            }
            imgHtml = "<img src='resources/MEDIA/images/file/"+ext+".gif' width=50 height=50/>";
        } else {
            imgHtml = "<img src='resources/MEDIA/images/file/txt.gif' width=50 height=50/>";
        }
        return imgHtml;
    };
    jQuery("#attachmentGird").jqGrid({
        url : 'attachment/queryAsList',
        datatype : "json",
        autowidth : true,
        rownumbers : true,
        height : 400,
        colNames : [ '文件ID', '分类ID', '文件名', '文件大小(byte)', '文件真实类型', '是否删除', '预览', '上传时间', '上传者', '操作' ],
        colModel : [ {
            name : 'fileid',
            index : 'fileid',
            key : true,
            hidden : true,
            align : 'center'
        }, {
            name : 'catalogid',
            index : 'catalogid',
            hidden : true
        }, {
            name : 'filename',
            index : 'filename',
            width : 150
        }, {
            name : 'filesize',
            index : 'filesize',
            hidden : true
        }, {
            name : 'filetype',
            index : 'filetype',
            hidden : true
        }, {
            name : 'isdelete',
            index : 'isdelete',
            hidden : true
        }, {
            name : 'preview',
            index : 'preview',
            align : 'center',
            width : 80
        }, {
            name : 'createtime',
            index : 'createtime'
        }, {
            name : 'creatorid',
            index : 'creatorid',
            align : 'center',
            width : 100
        }, {
            name : 'downloadOper',
            index : 'downloadOper',
            align : 'center',
            width : 100
        } ],
        rowNum : 15,
        rowList : [ 15, 20, 25, 30 ],
        pager : '#attachmentToolbar',
        recordpos : 'right',
        viewrecords : true,
        sortorder : "desc",
        jsonReader : {
            repeatitems : false
        },
        gridComplete : function() {
            var ids = jQuery("#attachmentGird").jqGrid('getDataIDs') || [];
            for ( var i = 0; i < ids.length; i++) {
                var id = ids[i];
                var attachment = jQuery("#attachmentGird").jqGrid('getRowData', id);
                var fileid = attachment['fileid'];
                var fileName = attachment['filename'];
                var fileType = attachment['filetype'];
                var downloadUrl = "<a href='attachment/download?fileid="+fileid+"' >下载</a>";
                var htmlImg = "";
                if(fileType.indexOf("image") != -1){
                    htmlImg = "<img src='attachment/preview?fileid="+fileid+"' />";
                }else{
                    htmlImg = iconFmt(fileName, fileType);
                }
                jQuery("#attachmentGird").jqGrid('setRowData', id, {
                    preview : htmlImg,
                    downloadOper : downloadUrl
                });
            }
        },
        multiselect : true,
        shrinkToFit : false,
        caption : "系统附件表列表"
    });
    
    jQuery("#attachmentGird").jqGrid('navGrid', '#attachmentToolbar', {
        edit : false,
        add : false,
        del : false,
        search : false,
        refresh : true
    }).navSeparatorAdd('#attachmentToolbar', {
        sepclass : 'ui-separator',
        sepcontent : ''
    }).navButtonAdd('#attachmentToolbar', {
        caption : "新增附件",
        buttonicon : "ui-icon ui-icon-plus",
        onClickButton : function() {
            var zTree = jQuery.fn.zTree.getZTreeObj("attachCatalogTree");
            var selectNodes = zTree.getSelectedNodes();
            if(selectNodes.length == 0){
                alert("请选择一个上传类别!");
                return;
            }
            var selectNode = selectNodes[0];
            var content = "<iframe frameborder='0' width='800' height='600' src='resources/upload.jsp?creatorid="+username+"&catalogid="+selectNode.catalogId+"'></iframe>";
            attachUploadDialog.set("content", content);
            attachUploadDialog.show();
        },
        position : "last"
    }).navButtonAdd('#attachmentToolbar', {
        caption : "删除附件",
        buttonicon : "ui-icon ui-icon-trash",
        onClickButton : function() {
            attachmentDelete();
        },
        position : "last"
    }).navButtonAdd('#attachmentToolbar', {
        caption : "勾选附件",
        buttonicon : "ui-icon ui-icon-pencil",
        onClickButton : function() {
            var dropId = "${dropTree.dropId}";
            var keyId = "${dropTree.keyId}";
            var ids = jQuery("#attachmentGird").jqGrid('getGridParam', 'selarrrow') || [];
            var k = "", v = "";
            for ( var i = 0; i < ids.length; i++) {
                var id = ids[i];
                var attachment = jQuery("#attachmentGird").jqGrid('getRowData', id);
                var fileId = attachment['fileid'];
                var fileName = attachment['filename'];
                k += fileId + ",";
                v += fileName + ",";
            }
            if (v.length > 0) {
                v = v.substring(0, v.length - 1);
                k = k.substring(0, k.length - 1);
            }
            var dispObj = jQuery("#" + dropId);
            var realObj = jQuery("#" + keyId);
            dispObj.attr("value", v);
            realObj.attr("value", k);
        },
        position : "last"
    });
</script>
